package top.stacktrace.BookInfo.service;

import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.stacktrace.BookInfo.dao.BookDao;
import top.stacktrace.BookInfo.domain.Book;

import java.util.List;
import java.util.Map;

@Service
public class BookService implements TccService {
    @Autowired
    private BookDao bookDao;

    @CacheEvict(value = "booklist",allEntries = true)
    public boolean addBook(Book b){
        return bookDao.saveBook(b) == 1;
    }

    @Cacheable(value="booklist")
    public List<Book> getBooks(){
        return bookDao.getBooks();
    }

    @Cacheable(value="book",key = "#id",unless = "#result == null")
    public Book getBookDetail(long id){
        return bookDao.getBookById(id);
    }

    public boolean setBookReserve(long id,int reserve){
        return bookDao.setReserve(id,reserve) == 1;
    }

    public boolean inCreaseReserve(long id,int reserve){
        return bookDao.inCreaseReserve(id,reserve) == 1;
    }

    @Transactional
    @Override
    public boolean reserve(long id,int reserve){
        int ret =  bookDao.deCreaseReserve(id,reserve);
        if(ret > 0){
            bookDao.saveXA(RootContext.getXID());
        }
        return ret > 0;
    }

    @Override
    public void commitTcc(BusinessActionContext context) {
        bookDao.delXA(context.getXid());
    }

    @Transactional
    @Override
    public void cancel(BusinessActionContext context) {
        if(bookDao.countXA(context.getXid()) > 0){
            bookDao.inCreaseReserve((int)context.getActionContext("bookid"),(int)context.getActionContext("reserve"));
            bookDao.delXA(context.getXid());
        }
    }
}
